using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEditor;

public class AddressableCustomGroupMgr 
{
    public static AddressableCustomGroup SetCustomGroupPath(string path)
    {
        var vs = path.Replace('\\', '/').Split('/');

        int groupId = 0;
        var groupName = string.Empty;
        var groupPath = string.Empty;

        for (int i = 0; i < vs.Length; i++)
        {
            if(vs[i]==AddressableBuildTools.addressAssets)
            {
                if (i + 1 >= vs.Length) continue;

                if (AddressableFolderEditor.baseTypeGroups.Contains(vs[i + 1]))
                {
                    if (i + 2 >= vs.Length) continue;

                    groupId = i + 2;
                    groupName = vs[groupId];

                    int count = 0;
                    while (count <= groupId)
                    {
                        groupPath += $"{vs[count++]}/"; 
                    }
                    groupPath = groupPath.Replace(AddressableBuildTools.AppDataPath.Replace('\\','/'),"").TrimStart('/').TrimEnd('/');
                }
            }
            continue; 
        }

        if (!string.IsNullOrEmpty(groupPath))
        {
            DirectoryInfo directory = new DirectoryInfo(groupPath);
            AddressableCustomGroup customGroup = null;

            string customPath = $"{ directory.FullName}/CustomGroup.asset";
            string savePath  = $"{ groupPath}/CustomGroup.asset";
            if (!File.Exists(customPath))
            {
                customGroup = ScriptableObject.CreateInstance<AddressableCustomGroup>();
                AssetDatabase.CreateAsset(customGroup, savePath);
                AssetDatabase.Refresh();
            }
            else
            {
                customGroup = AssetDatabase.LoadAssetAtPath<AddressableCustomGroup>(savePath);
            }

            customGroup.groupName = groupName.Replace(AddressableBuildTools.GroupTag,"");
            customGroup.addressType = groupPath.Contains("AddressableAssets/Remoted") ? AddressType.Remoted : AddressType.Local;
            return customGroup;
        }

        return null;
    }

  
}

